package com.eastedu.superise.handler.ulearning;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ConcurrentHashSet;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastedu.client.file.model.FileInfoResponse;
import com.eastedu.exception.ServiceException;
import com.eastedu.manager.FileManager;
import com.eastedu.repository.file.FileOriginalMapper;
import com.eastedu.repository.file.FileOriginalPO;
import com.eastedu.repository.file.FileState;
import com.eastedu.repository.ulearning.mapper.LearningFileMapper;
import com.eastedu.repository.ulearning.po.TmpFilePO;
import com.eastedu.superise.handler.AbstractFileArchiveRollbackTemplate;
import com.eastedu.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.sql.SQLException;
import java.util.Objects;

/**
 * 【回滚】文件归档
 *
 * @author zhangzhishuai
 */
@Slf4j
@Service
@DS("learning")
public class LearningFileArchiveRollbackHistoricalDataHandler extends AbstractFileArchiveRollbackTemplate<TmpFilePO> {

    private final LearningFileMapper learningFileMapper;
    private final FileManager fileManager;
    private final FileOriginalMapper fileOriginalMapper;
    private final ConcurrentHashSet<String> fileIds = new ConcurrentHashSet<>();

    public LearningFileArchiveRollbackHistoricalDataHandler(LearningFileMapper learningFileMapper,
                                                            FileManager fileManager,
                                                            FileOriginalMapper fileOriginalMapper,
                                                            JdbcTemplate jdbcTemplate) {
        super(fileManager, jdbcTemplate);
        this.learningFileMapper = learningFileMapper;
        this.fileManager = fileManager;
        this.fileOriginalMapper = fileOriginalMapper;
    }

    @Override
    public void start() {
        super.start();
        this.learningFileMapper.updateByBak();
    }

    @Override
    protected String getSql() {
        return "select * from t_tmp_file";
    }

    @Override
    public void callback(TmpFilePO po) throws SQLException {

        String fileId = po.getFileId();
        try {
            FileOriginalPO fileInfo = fileOriginalMapper.selectById(fileId);
            // 只处理已归档的文件
            if (!Objects.equals(fileInfo.getState(), FileState.ARCHIVED)) {
                log.error("{}:文件不是已归档状态，当前状态为：{}", fileId, fileInfo.getState());
                return;
            }
            Path originalFilePath = download(fileId, fileInfo);
            upload(fileInfo, originalFilePath);
            updateResourceByFileId(fileId, po.getBPath());
            FileUtils.deletePath(originalFilePath);

        } catch (Exception e) {
            log.error("{}:查询文件信息异常：{}", fileId, e.getMessage(), e);
            fileIds.add(String.valueOf(po.getFileId()));
        }
        if (CollUtil.isNotEmpty(fileIds)) {
            log.info("文件回滚失败的资源ID: {}", this.fileIds);
        }
    }

    private void updateResourceByFileId(String fileId, String path) {
            try {
                FileInfoResponse fileInfoResponse = fileManager.getFileInfo(Long.valueOf(fileId));
                if (Objects.isNull(fileInfoResponse)) {
                    log.warn("文件信息错误，跳过，ID：{}", fileId);
                    return;
                }
                this.learningFileMapper.updateFileByPath(fileId, fileInfoResponse.getUrls().getPreview(), fileInfoResponse.getMd5(), path);
                this.learningFileMapper.updateVodLessonByPath(fileId, fileInfoResponse.getUrls().getPreview(), path);
            } catch (Exception e) {
                throw new ServiceException(e, "文件更新异常");
            }
    }


    @Override
    public void afterCompletion() {
        super.afterCompletion();
        log.info("文件归档失败的资源id: {}", this.fileIds);
    }

}
